package com.b2bpsssm.interceptor;/**
 * @author JunYu
 * @create 2022-08-12--11:26
 */

import com.b2bpsssm.utils.JwtResult;
import com.b2bpsssm.utils.JwtUtils;
import org.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: B2BPSSMSystem
 * @description: 总拦截器，主要用于拦截除login以外的所有请求，用于验证token。
 * @author: JunYu
 * @create: 2022-08-12 11:26
 **/

public class TotalInterceptor implements HandlerInterceptor {
    //在进入控制器之前执行，如果返回FALSE阻止控制器执行
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        boolean result = true;
        String token = httpServletRequest.getHeader("Authorization");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        Map map = new HashMap<>();
        if(token!=null&&!"".equals(token))
        {
            JwtResult jwtResult = JwtUtils.validateJwt(token);
            result = jwtResult.isSuccess();
            if(result){//token
                //放行
                return true;
            }else{
                map.put("code",jwtResult.getErrCode());
                if(jwtResult.getErrCode() == 1005){
                    map.put("msg","Token过期");
                }else if(jwtResult.getErrCode() == 1006){
                    map.put("msg","Token验证失败");
                }
            }
        }else{
            map.put("code",500);
            map.put("msg","Token不能为空");
        }
        httpServletResponse.getWriter().write(JSONObject.valueToString(token));
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
        return false;
    }
    //在控制器执行完毕，未（未返回ModelAndView）返回值时执行，一般用于日志打印，敏感词过滤
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }
    //在整个流程执行完后执行，注意用于记录执行流程中出现的异常
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
